package eu.goldenak.ircbot;

import java.util.Date;
import java.util.TimerTask;

/**
 * This class used to create a timer in this bot.
 */
public abstract class BotTimer extends TimerTask {
	
	/**
	 * The unique timer ID for this timer, which will be used for identification
	 * purposes.
	 */
	private int m_nTimerId;
	
	/**
	 * A timer is mostly used to repeat a certain task at a specified interval.
	 * That interval is specified here. The interval is specified in
	 * milliseconds.
	 */
	private int m_nInterval;
	
	/**
	 * Sometimes, we just want a BotTimer which executes once at a certain time.
	 * In that case, we set this property to false. After the BotTimer has been
	 * executed, it will be deleted.
	 */
	private boolean m_bRepeating;
	
	/**
	 * The constructor registers this class with the TimerManager automatically,
	 * with the default settings. That means it directly executes after been
	 * scheduled, once.
	 */
	public BotTimer () {
		m_nInterval  = 0;
		m_bRepeating = false;
		
		register ();
	}
	
	/**
	 * The constructor registers this class with the TimerManager automatically.
	 * This one executes the timer only once; at the specified timestamp that
	 * is. If the supplied Date is in the past however, an
	 * IllegalArgumentException is raised.
	 */
	public BotTimer (Date pDate) {
		m_nInterval = (int) (pDate.getTime () - new Date ().getTime ());
		
		if (m_nInterval < 0) {
			// Setting a BotTimer in the past is not supported, unfortunately.
			throw new IllegalArgumentException ("The difference between now " +
				"and the time to execute is negative.");
		}
		
		register ();
	}
	
	/**
	 * The constructor registers this class with the TimerManager automatically.
	 * Difference here is that we take two parameters, one for the delay, and
	 * one to specify if the TimerTask should be repeated.
	 */
	public BotTimer (int nInterval, boolean bRepeating) {
		m_nInterval  = nInterval;
		m_bRepeating = bRepeating;
		
		register ();
	}
	
	/**
	 * This method will be used to register this BotTimer with the TimerManager.
	 */
	private void register () {
		m_nTimerId = TimerManager.getInstance ().register (this);
	}
	
	/**
	 * Returns the timer ID for this BotTimer.
	 */
	public final int getTimerId () {
		return m_nTimerId;
	}
	
	/**
	 * Returns the interval at which this BotTimer should be executed.
	 */
	public final int getInterval () {
		return m_nInterval;
	}
	
	/**
	 * Returns whether this BotTimer should be repeated at the specified
	 * interval.
	 */
	public final boolean isRepeating () {
		return m_bRepeating;
	}
}